package solution.T0215_1_Clipboard;

import solution.T0215_1_Clipboard.command.Command;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class CommandExecutor extends Thread {
    private final BlockingQueue<Command> queue = new LinkedBlockingQueue<>();
    private volatile boolean running = true;

    public void submit(Command command) {
        try {
            queue.put(command); // 阻塞式提交命令
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public void stopExecutor() {
        running = false;
        this.interrupt();
    }

    @Override
    public void run() {
        while (running) {
            try {
                Command command = queue.take(); // 取出并执行命令
                command.execute();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
